// pages/reserve/reserve.js
const util = require('../../utils/util.js');
const api = require('../../config/api.js');
const app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    selusertype: '请选择使用者类型',
    usertypedata: [],
    selarea: '请选择区域',
    areadata: [],
    selstreet: '请选择街道',
    streetdata: [],
    selcommunity: '请选择社区',
    communitydata: [],
    selreservetime: '请选择时间段',
    reservetimedata: [],

    
    // 用于提交的数据
    userReserveInfo: {
      cont: 3,
      userid: 0,
      name: '',
      sex: 0, //1.man 2woman
      mobile: '',
      codeid: '',
      usertype: 0,
      address: '',
      time: '请选择预约时间',
      area: 0,
      street: 0,
      community: 0,
      reservetimeid: 0,
      floor: '',
      service:0
    },




    openSelectRegion: false, // 选择服务地址
    isReserveTime:false,
    full_region: '',

    selectRegionList: [{
        id: 0,
        name: '区域',
        parent_id: 1,
        type: 1
      },
      {
        id: 0,
        name: '街道',
        parent_id: 1,
        type: 2
      },
      {
        id: 0,
        name: '社区',
        parent_id: 1,
        type: 3
      }
    ],
    regionType: 1,
    regionList: [],
    selectRegionDone: false,


  },
  //listitem 点击
  selectRegion(event) {
    let that = this;
    let regionIndex = event.target.dataset.regionIndex;
    let regionItem = this.data.regionList[regionIndex];
    let regionType = regionItem.type;
    let selectRegionList = this.data.selectRegionList;
    selectRegionList[regionType - 1] = regionItem;


    if (regionType != 3) {
      this.setData({
        selectRegionList: selectRegionList,
        regionType: regionType + 1
      })

      this.getRegionList(regionItem.id, regionItem.type+1);
    } else {
      this.setData({
        selectRegionList: selectRegionList
      })
    }

    //重置下级区域为空
    selectRegionList.map((item, index) => {
      if (index > regionType - 1) {
        item.id = 0;
        item.name = index == 1 ? '街道' : '社区';
        item.parent_id = 0;
      }
      return item;
    });

    this.setData({
      selectRegionList: selectRegionList
    })


    that.setData({
      regionList: that.data.regionList.map(item => {

        //标记已选择的
        if (that.data.regionType == item.type && that.data.selectRegionList[that.data.regionType - 1].id == item.id) {
          item.selected = true;
        } else {
          item.selected = false;
        }

        return item;
      })
    });

    this.setRegionDoneStatus();

  },
  //  区域   街道  社区选择
  selectRegionType(event) {
    let that = this;
    let regionTypeIndex = event.target.dataset.regionTypeIndex;
    let selectRegionList = that.data.selectRegionList;

    //判断是否可点击
    if (regionTypeIndex + 1 == this.data.regionType || (regionTypeIndex - 1 >= 0 && selectRegionList[regionTypeIndex - 1].id <= 0)) {
      return false;
    }

    this.setData({
      regionType: regionTypeIndex + 1
    })

    let selectRegionItem = selectRegionList[regionTypeIndex];

    this.getRegionList(selectRegionItem.parent_id, selectRegionItem.type);

    this.setRegionDoneStatus();

  },

  // 点击了遮盖层 取消
  cancelSelectRegion() {
    this.setData({
      openSelectRegion: false,
      regionType: this.data.regionDoneStatus ? 3 : 1
    });

  },
  // 确认按钮 是否可点击
  setRegionDoneStatus() {
    let that = this;
    let doneStatus = that.data.selectRegionList.every(item => {
      return item.id != 0;
    });

    that.setData({
      selectRegionDone: doneStatus
    })

  },

  // 点击  弹出区域的选择
  chooseRegion() {
    let that = this;
    this.setData({
      openSelectRegion: !this.data.openSelectRegion
    });
    let reserve = that.data.userReserveInfo;

    //设置区域选择数据
    /**
     * area: 0,
      street: 0,
      community: 0,
          selarea: '请选择区域',
    areadata: [],
    selstreet: '请选择街道',
    streetdata: [],
    selcommunity: '请选择社区',
     */
    // let address = this.data.address;
    if (reserve.area > 0 && reserve.street > 0 && reserve.community > 0) {
      let selectRegionList = this.data.selectRegionList;
      selectRegionList[0].id = reserve.area;
      selectRegionList[0].name = that.data.selarea;
      selectRegionList[0].parent_id = 1;

      selectRegionList[1].id = reserve.street;
      selectRegionList[1].name = that.data.selstreet;
      selectRegionList[1].parent_id = reserve.area;

      selectRegionList[2].id = reserve.community;
      selectRegionList[2].name = that.data.selcommunity;
      selectRegionList[2].parent_id = reserve.street;

      this.setData({
        selectRegionList: selectRegionList,
        regionType: 3
      });

      this.getRegionList(reserve.street,3);
    } else {
      this.setData({
        selectRegionList: [{
            id: 0,
            name: '区域',
            parent_id: 1,
            type: 1
          },
          {
            id: 0,
            name: '街道',
            parent_id: 1,
            type: 2
          },
          {
            id: 0,
            name: '社区',
            parent_id: 1,
            type: 3
          }
        ],
        regionType: 1
      })
      this.getRegionList(0,1);
    }

    this.setRegionDoneStatus();

  },
  // 获取地址列表
  getRegionList(regionId,types) {

    console.log(regionId);
    let that = this;
    let regionType = that.data.regionType;
    util.request(api.Reserve, {
      'parentid': regionId,
      'type': types,
      'cont': 2
    }, 'POST').then(function(res) {
      console.log(res);
      if (res.code === 0) {

        that.setData({
          regionList: res.data.map(item => {

            //标记已选择的
            if (regionType == item.type && that.data.selectRegionList[regionType - 1].id == item.id) {
              item.selected = true;
            } else {
              item.selected = false;
            }

            return item;
          })
        });

      }
    });
  },
  // 确认选择
  doneSelectRegion() {
    if (this.data.selectRegionDone === false) {
      return false;
    }


    let reserve = this.data.userReserveInfo;
    let selectRegionList = this.data.selectRegionList;
    reserve.area = selectRegionList[0].id;
    reserve.street = selectRegionList[1].id;
    reserve.community = selectRegionList[2].id;


    let full_region = selectRegionList.map(item => {
      return item.name;
    }).join('');

    this.setData({
      selarea: selectRegionList[0].name,
      selstreet: selectRegionList[1].name,
      selcommunity: selectRegionList[2].name,
      full_region: full_region,
      reserve: reserve,
      openSelectRegion: false
    });
    this.getReserveTime();

  },






  /**
   * 姓名
   */
  bindinputName(event) {
    let reserve = this.data.userReserveInfo;
    reserve.name = event.detail.value;
    // console.log(event.detail.value);
    this.setData({
      userReserveInfo: reserve
    })
  },
  /**
   * 性别
   */
  bindIsMan: function(event) {
    //  console.log(event.target.dataset.isman);
    var sex = event.target.dataset.isman;
    let reserve = this.data.userReserveInfo;
    reserve.sex = sex;
    this.setData({
      userReserveInfo: reserve
    })
  },
  // 手机
  bindinputMobile(event) {
    let reserve = this.data.userReserveInfo;
    reserve.mobile = event.detail.value;
    this.setData({
      userReserveInfo: reserve
    });
  },
  // 身份证
  bindinputIdcard(event) {
    let reserve = this.data.userReserveInfo;
    reserve.codeid = event.detail.value;
    this.setData({
      userReserveInfo: reserve
    });
  },
  /**
   * 使用者类型
   */
  bindPickerProvinceChange: function(e) {
    var that = this;
    let reserve = this.data.userReserveInfo;
    var selItem = that.data.usertypedata[e.detail.value].name;
    reserve.usertype = that.data.usertypedata[e.detail.value].id;
    this.setData({
      selusertype: selItem,
      userReserveInfo: reserve

    })

  },
  // 详细地址
  bindinputAddress(event) {
    let reserve = this.data.userReserveInfo;
    reserve.address = event.detail.value;
    this.setData({
      userReserveInfo: reserve
    });
  },
  //楼层
  bindinputFloor(event) {
    let reserve = this.data.userReserveInfo;
    reserve.floor = event.detail.value;
    this.setData({
      userReserveInfo: reserve
    });
  },

  //  预约时间
  bindDateChange: function(e) {
    let that = this;
    console.log(e.detail.value)
    let reserve = this.data.userReserveInfo;
    reserve.time = e.detail.value;
    this.setData({
      userReserveInfo: reserve
    })
    that.getReserveTime();
  },



  /**
   * 服务点选择
   *  
   */

  // 时间
  selReserveTime: function(e) {
    var index = e.detail.value;
    let that = this;
    let reserve = that.data.userReserveInfo;
    reserve.reservetimeid = that.data.reservetimedata[index].id;

    let selreservetime = that.data.reservetimedata[index].info;
    that.setData({
      selreservetime: selreservetime,

      userReserveInfo: reserve,
    })
  },

  getReserveTime() {
    let that = this;
    let reserve = that.data.userReserveInfo;
    if (reserve.time == '请选择预约时间' || reserve.community == 0) {
      return;
    }
    
    util.request(api.Reserve, {
      'cont': '4',
      'time': reserve.time,
      'communityid': reserve.community
    }, 'POST').then(function(res) {
      console.log(res);
      if (res.code == 0) {
        that.setData({
          isReserveTime:true,
          reservetimedata: res.data,
        })
      }
    });
  },


  /**
   * 提交订单
   */
  saveOrder: function(e) {
    let that = this;
    let reserve = that.data.userReserveInfo;
    console.log(reserve);
    if (that.validate()) {

      
      util.request(api.Order, reserve, 'POST').then(function(res) {
        console.log(res);
        if (res.code == 0) {


          wx.showToast({
            title: '预约成功',
            icon: 'success',
            duration: 2000,
          })

          // wx.redirectTo({
          //   url: '../orderdetails/orderdetails?orderId=' + res.data.orderid
          // })
         wx.navigateBack();

          that.setData({


          })

        }
      });
    }

  },


  validate() {
    let that = this;
    let reserve = that.data.userReserveInfo;
    if (reserve.name == '') {
      util.showErrorToast("请输入姓名");
      return false;
    }
    if (reserve.sex == 0) {
      util.showErrorToast("请选择性别");
      return false;
    }
    if (reserve.mobile == '') {
      util.showErrorToast("请输入手机号");
      return false;
    }
    //手机号正则  
    var phoneReg = /(^1[3|4|5|7|8]\d{9}$)|(^09\d{8}$)/;
    //电话  
    if (!phoneReg.test(reserve.mobile)) {
      util.showErrorToast('手机号码有误');
      return false;
    }
    if (reserve.codeid == '') {
      util.showErrorToast("请输入身份证号码");
      return false;
    }
    var reg = /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/;
    if (!reg.test(reserve.codeid)) {
      util.showErrorToast('身份证号码有误');
      return false;
    }
    if (reserve.usertype == 0) {
      util.showErrorToast("请选择使用者类别");
      return false;
    }
    if (reserve.address == '') {
      util.showErrorToast("请输入详细地址");
      return false;
    }
    // floor
    if (reserve.floor == '') {
      util.showErrorToast("请输入使用楼层");
      return false;
    }
    if (reserve.time == '请选择预约时间') {
      util.showErrorToast("请选择预约时间");
      return false;
    }
    let thistime = Date.parse(util.formatTime(new Date())) ;
    let seltime = Date.parse(reserve.time);
    console.log(seltime - thistime); 

    if (seltime - thistime <=0) {
      util.showErrorToast("需提前一天预约");
      return false;
    }


    if (reserve.area == 0) {
      util.showErrorToast("请选择区域");
      return false;
    }
    if (reserve.street == 0) {
      util.showErrorToast("请选择街道");
      return false;
    }
    if (reserve.community == 0) {
      util.showErrorToast("请选择社区");
      return false;
    }
    if (reserve.reservetimeid == 0) {
      util.showErrorToast("请选择服务时间段");
      return false;
    }



    return true;

  },


  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {

    console.log(options);
    let that = this;
    let reserve = that.data.userReserveInfo;
    reserve.service=options.serviceId
    this.setData({
      userReserveInfo: reserve
    });

    

    let userids = wx.getStorageSync('userids');

    util.request(api.Reserve, {
      'cont': '1'
    }, 'POST').then(function(res) {
      console.log(res);
     
      if (res.code == 0) {
        let reserve = that.data.userReserveInfo;
        reserve.userid = userids;
        that.getHistory();
        that.setData({
         
          usertypedata: res.data.usertype,
          areadata: res.data.ragion,

          userReserveInfo: reserve,

        });
       

      } else {
        // wx: wx.showToast({
        //   title: '数据初始化失败请检查网络并刷新当前页面',
        //   icon: 'none',
        //   image: '',
        //   duration: 2000
        // })
      }
    });
 
    this.getRegionList(0,1);
  },
  getHistory: function (){
    let that =this;
    let reserve = this.data.userReserveInfo;
    console.log(reserve);
    let userids = reserve.userid
    util.request(api.Reserve, {
      'cont': '6',
      'userid': userids

    }, 'GET').then(function (res) {
      console.log(res);
      if (res.code == 0) {
       
        //reserve = res.data;
       //reserve.time = '请选择预约时间';
        reserve.name = res.data.name;
        reserve.address = res.data.address;
        reserve.codeid = res.data.codeid;
        reserve.floor = res.data.floor;
        reserve.sex = res.data.sex;
        reserve.mobile = res.data.mobile;
        reserve.usertype = res.data.usertype;


        let usertype =   that.data.usertypedata[res.data.usertype].name;
        console.log(usertype)
        that.setData({

          selusertype:usertype,
          userReserveInfo: reserve,
          
        })

      } else if (res.code == 400){

      } else {
        wx: wx.showToast({
          title: '数据初始化失败请检查网络并刷新当前页面ttt',
          icon: 'none',
          image: '',
          duration: 2000
        })
      }
    });
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {
 
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {
    let thistime = util.formatTime(new Date());
    console.log(thistime);

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {

  }
})